from zipfile import ZipFile
import click
import zipfile
import os

@click.command(help="""压缩和解压ZIP文件,默认是压缩,请是使用--help查看帮助\n
    ZipHelper --source 需要压缩的目录路径 --dest 输出的zip路径\n
    ZipHelper -unzip --source 需要解压缩的zip路径 --dest 解压到的输出目录路径""")
@click.option('-unzip',is_flag=True, help="解压") 
@click.option('--source',default="",help="zip内文件") 
@click.option('--insource',default="",help="zip内文件")
@click.option('--dest',default="",help="zip内文件")
@click.pass_context 
def runZipOrUnzip(ctx,unzip,source,insource,dest):
    print(" \n unzip: %s\n source: %s\n insource: %s\n dest %s\n" 
        % (unzip,source,insource,dest))

    if(len(source) == 0 or len(dest) == 0):
        return

    if(unzip):
        with ZipFile(source) as f:
            if(len(insource) == 0):
                f.extractall(path = dest)
            else:
                f.extract(path = dest,member =insource)
    else:
        with ZipFile(dest,'w',zipfile.ZIP_DEFLATED) as z:
            for dirpath, dirnames, filenames in os.walk(source):
                fpath = dirpath.replace(source,'')
                fpath = fpath and fpath + os.sep # + 优先级 > and
                for filename in filenames:
                    z.write(os.path.join(dirpath, filename),fpath+filename)
                    print ('==压缩成功==')
        pass
    pass

if __name__ == "__main__":
    print("Hello ZipHelper!")
    runZipOrUnzip(obj = {})
    print("Done ZipHelper!")
    
    pass